package com.fla.puzzle;

import java.util.ArrayList;
import java.util.List;

import com.fla.puzzle.pack.PackItem;

import android.content.SharedPreferences;

public class CompletedManager {
    public interface OnPackItemCompletedListener {
        void onPackItemCompleted(PackItem packItem);
    }

    private List<OnPackItemCompletedListener> listeners;

    private final SharedPreferences preferences;

    public CompletedManager(SharedPreferences preferences) {
        this.preferences = preferences;
        this.listeners = new ArrayList<CompletedManager.OnPackItemCompletedListener>();
    }

    public void addOnPackItemCompletedListener(OnPackItemCompletedListener listener) {
        listeners.add(listener);
    }

    public void removeOnPackItemCompletedListener(OnPackItemCompletedListener listener) {
        listeners.remove(listener);
    }

    public void markCompleted(PackItem packItem) {
        preferences.edit().putBoolean(createKey(packItem), true).commit();
        notifyCompleted(packItem);
    }

    public boolean isCompleted(PackItem packItem) {
        return preferences.getBoolean(createKey(packItem), false);
    }

    private String createKey(PackItem packItem) {
        return packItem.getPackId() + packItem.getId();
    }

    private void notifyCompleted(PackItem packItem) {
        for (OnPackItemCompletedListener completedListener : listeners) {
            completedListener.onPackItemCompleted(packItem);
        }
    }
}
